# main.py - FastAPI主应用
# -*- coding: UTF-8 -*-
import logging
import json
from fastapi import FastAPI, HTTPException, Request
from config import settings, logger
from llm_client import VolcanoLLM
from prompt_templates import (
    SYSTEM_PROMPT_ANALYSIS,
    USER_PROMPT_TEMPLATE_ANALYSIS,
    SYSTEM_PROMPT_REVISION,
    USER_PROMPT_TEMPLATE_REVISION
)

app = FastAPI(title="飞书表格与火山模型集成API")


@app.post("/api/content-revised")
async def run_process(request: Request):
    """执行完整的处理流程，从JSON输入中获取数据"""
    try:
        logger.info("===== 开始执行处理流程 =====")

        # 获取请求体中的JSON数据
        input_data = await request.json()
        logger.debug(f"接收到的输入数据: {json.dumps(input_data, ensure_ascii=False)}")

        # 提取content作为全文
        content = input_data.get("content", "")
        ProductHighlights = input_data.get("ProductHighlights", "")
        if not content:
            logger.error("输入数据中缺少content字段")
            raise HTTPException(status_code=400, detail="输入数据中缺少content字段")

        # 提取所有的quote和text对
        amendments = []
        i = 1
        while True:
            quote_key = f"quote{i}"
            text_key = f"text{i}"

            if quote_key in input_data and text_key in input_data:
                amendments.append({
                    "quote": input_data[quote_key],
                    "text": input_data[text_key]
                })
                i += 1
            else:
                break

        if not amendments:
            logger.error("输入数据中缺少quote和text对")
            raise HTTPException(status_code=400, detail="输入数据中缺少quote和text对")

        logger.info(f"找到 {len(amendments)} 个修改意见")

        # 构建修改意见字符串
        amendment_text = ""
        for idx, amendment in enumerate(amendments, 1):
            amendment_text += f"修改意见 {idx}:\n"
            amendment_text += f"原文引用: {amendment['quote']}\n"
            amendment_text += f"修改建议: {amendment['text']}\n\n"

        # 清理文本
        logger.info("开始清理文本数据")
        cleaned_content = content  # 这里可以根据需要添加清理逻辑
        cleaned_amendment = amendment_text  # 这里可以根据需要添加清理逻辑

        # 记录清理后的文本长度
        logger.debug(f"清理后的全文长度: {len(cleaned_content)}")
        logger.debug(f"清理后的修订意见长度: {len(cleaned_amendment)}")

        # 初始化火山模型客户端
        llm_client = VolcanoLLM(
            api_key=settings.volcano_api_key,
            model_name=settings.volcano_model
        )

        # 第一步：将content和amendment放入火山模型，生成修改意见解析
        logger.info("第一步：生成修改意见解析")

        # 确保内容不为空
        if not cleaned_amendment or not cleaned_content:
            logger.error("修订意见或原稿内容为空，无法继续处理")
            raise HTTPException(status_code=400, detail="修订意见或原稿内容为空")

        # 格式化用户提示词
        analysis_user_prompt = USER_PROMPT_TEMPLATE_ANALYSIS.format(
            manuscript=cleaned_content,
            amendment=cleaned_amendment,
            ProductHighlights=ProductHighlights
        )
        logger.debug(f"第一次调用的完整提示词: {analysis_user_prompt}")
        logger.debug(f"分析提示词长度: {len(analysis_user_prompt)}")

        analysis_result = llm_client.generate(
            system_prompt=SYSTEM_PROMPT_ANALYSIS,
            user_prompt=analysis_user_prompt
        )

        if not analysis_result or analysis_result.startswith("处理失败"):
            logger.error("修改意见解析生成失败，终止流程")
            raise HTTPException(status_code=500, detail="修改意见解析生成失败")

        # 第二步：将修改意见细则与content再次放入火山模型，生成最终修订文本
        logger.info("第二步：生成最终修订文本")

        revision_user_prompt = USER_PROMPT_TEMPLATE_REVISION.format(
            manuscript=cleaned_content,
            analysis=analysis_result,
            ProductHighlights=ProductHighlights
        )

        logger.debug(f"修订提示词长度: {len(revision_user_prompt)}")

        revision_result = llm_client.generate(
            system_prompt=SYSTEM_PROMPT_REVISION,
            user_prompt=revision_user_prompt
        )

        if not revision_result or revision_result.startswith("处理失败"):
            logger.error("最终修订文本生成失败，终止流程")
            raise HTTPException(status_code=500, detail="最终修订文本生成失败")

        logger.info("===== 处理流程执行成功 =====")
        return {
            "status": "success",
            "content": cleaned_content,
            "amendments": amendments,
            "analysis_result": analysis_result,
            "revision_result": revision_result
        }

    except HTTPException:
        raise
    except Exception as e:
        logger.critical(f"处理流程发生未预期错误：{str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail="服务器内部错误，请查看日志获取详细信息")


@app.get("/")
async def root():
    """API根端点，提供基本信息"""
    return {
        "message": "飞书表格与火山模型集成API",
        "endpoints": {
            "/run-process": "POST - 执行完整的处理流程",
            "/docs": "API文档"
        }
    }


if __name__ == "__main__":
    import uvicorn

    logger.info("启动FastAPI服务...")
    uvicorn.run(app, host="0.0.0.0", port=8851)